package com.gh.controller;

import com.alibaba.fastjson.JSONObject;
import com.gh.helper.JwtHelper;
import com.gh.model.user.UserInfo;
import com.gh.result.Result;
import com.gh.service.UserInfoService;
import com.gh.util.ConstantWxUtils;
import com.gh.util.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Eric
 * @Date 2021/6/19 15:34
 * @Version 1.0
 */
@Controller
@RequestMapping("/api/user/wx")
@Slf4j
public class WxApiController {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 微信扫码登录回调
     */
    @GetMapping("callback")
    public String callback(String code, String state) {
        //拿着临时票据code和微信id和密钥，请求微信固定地址，得到两个值accessToken和openId
        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                code);
        try {
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            //判断数据库是否存在扫描人信息
            UserInfo userInfo = userInfoService.findByOpenId(openid);
            if (userInfo == null) {
                //拿着access_token和openid去请求微信地址，得到扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultUserInfo = HttpClientUtils.get(userInfoUrl);
                JSONObject object = JSONObject.parseObject(resultUserInfo);
                //解析用户信息
                String headimgurl = object.getString("headimgurl");
                String nickname = object.getString("nickname");
                //添加数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.insert(userInfo);
            }
            //返回name和token字符串
            Map<String, Object> map = new HashMap<>();
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            //  前端判断openid不为空，需要绑定手机号，如果为空不要绑定手机号
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", openid);
            } else {
                map.put("openid", "");
            }
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            return "redirect:" + ConstantWxUtils.YYGH_BASE_URL + "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取二维码相关参数
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result getLoginParam() {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", ConstantWxUtils.WX_OPEN_APP_ID);
        map.put("scope", "snsapi_login");
        //对redirect_url进行URLEncoder编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("redirectUrl", redirectUrl);
        map.put("response_type", "code");
        map.put("state", "Eric");
        return Result.ok(map);
    }
}
